/*
 * @Author: Lin Hongwei
 * @Date: 2022-09-09 22:23:42
 * @LastEditTime: 2022-10-31 18:40:07
 * @LastEditors: Lin Hongwei
 * @email: 1365755396@qq.com
 * @CSDN: https://blog.csdn.net/weixin_45429409
 * @Description: 登录逻辑的context数据共享
 */
import React, {
  Dispatch,
  SetStateAction,
  ReactNode,
  useContext,
  useState,
} from "react";
import { useQueryClient } from "react-query";
import * as AuthApi from "../api/login";
import { useMount } from "../hooks";
import { User } from "../types/user";
interface AuthForm {
  name: string;
  pass: string;
}

//创建一个context对象,设置默认值为undefined
const AuthContext = React.createContext<
  | undefined
  | {
      user: User | null;
      login: (form: AuthForm) => Promise<void>;
      register: (form: AuthForm) => Promise<void>;
      loginOut: () => void;
    }
>(undefined);

/**
 * @description: 提供Provider组件
 * @param {object} props:{children(子组件)}
 * @return {*} 返回一个Provider组件，通过value传递共享数据，children接受子组件
 */
export const AuthProvider = ({ children }: { children: ReactNode }) => {
  const [user, setUser] = useState<User | null>(null);
  //初始化用户信息
  useMount(() => {
    initUser().then(setUser);
  });

  const login = (form: AuthForm) =>
    AuthApi.login(form).then((user) => setUser(user));
  const register = (form: AuthForm) =>
    AuthApi.register(form).then((res) => console.log("注册成功----", res));

  //清除react-query的缓存
  const queryClient = useQueryClient();
  const loginOut = () =>
    AuthApi.loginOut().then(() => {
      setUser(null);
      queryClient.clear(); //清除所有缓存
    });
  return (
    <AuthContext.Provider
      children={children}
      value={{ user, login, register, loginOut }}
    />
  );
};

/**
 * @description: 提供访问数据的hook
 * @return {*} 返回获取到的数据
 */
export const useAuthContextHook = () => {
  const context = useContext(AuthContext);
  if (!context) {
    throw Error("useAuthHook只能在AuthProvider组件中使用！");
  }
  return context;
};

/**
 * @description: 初始化获取用户信息
 * @return {*}
 */
// export const initUser = () => {
//   let user = AuthApi.getUser();
//   console.log("获取-------",user)
//   return Promise.resolve(user);
// }
export const initUser = async () => {
  let user = AuthApi.getUser();
  console.log("获取用户信息-------", user);
  return user;
};
